package CollectionChannelFactory;
use strict;
use YAML;
use DataCollectionChannel;

sub new{
	my $self = {};
	bless $self;
	return $self;
}

############################################################
##	Load channel from yaml config file 				      ##
##  input: the file name			   				      ##
##  output: the array of DataCollectionChannel subobjects ##
##          (channel adapter objects)					  ## 
############################################################ 
sub load_channels_from_yaml_file{
	my $self = shift;
	my $config_file = shift;
	my @array_hashref = YAML::LoadFile($config_file);	# load the file
	if (!@array_hashref){
		return(undef, "The configuration file is in wrong format");
	}else{
		my $channels = [];
		foreach my $hashref (@array_hashref){
			my $subclass = $hashref->{adapter}; # the adapter class name
			my $tmp = DataCollectionChannel::new($subclass); # create channel adapter objects		
			$tmp->copy($hashref);	# copy the configuration hash to the channel adapter object		
			push @$channels, $tmp;  # put the adapter to the channel array
		}
		return ($channels, "Successfully loaded"); 
	} 	
}

##################################################
## input: 									    ##
##		$name the channel name				    ##	
##		$channels the channel array reference   ##
## output: 									    ##
##		the channel object whose name is $name  ##
##################################################
sub get_channel_by_name{	
	my $self = shift;
	my $name = shift; # the channel name	
	my $channels = shift;
	if ($name eq "" || !ref($channels)){
		return (undef, "The company code or security_center_code is empty");
	}else{
		foreach my $channel (@{$channels}){
			if (lc($name) eq lc($channel->{NAME})){
				return ($channel, "Found one channel");
			}
		}
		return (undef, "Found none channel with name: $name"); 
	}
	
}

##################################################
## input: 									    ##
##		$center the center object 				    ##	
##		$channels the channel array reference   ##
## output: 									    ##
##		the channel objects whose security_center_code is the code of the center  ##
##################################################
sub get_channels_by_center{	
	my $self = shift;
	my $center = shift; # the channel name	
	my $channels = shift;
	my $channels_by_center = [];
	if (!defined($center) || !ref($channels)){
		return undef;
	}else{
		foreach my $channel (@{$channels}){
			if (lc($center->code()) eq lc($channel->security_center_code())){
				push @{$channels_by_center}, $channel;				
			}
		}		 
		return $channels_by_center;
	}	
}

sub DESTROY{
	
}
 
1;